package cn.jsu.oj.judgment.net.netHandler;

import cn.jsu.oj.judgment.factory.CmdHandleFactory;
import cn.jsu.oj.judgment.factory.JudgeFactory;
import cn.jsu.oj.judgment.handle.CommandPack;
import cn.jsu.oj.judgment.net.starter.JudgeStarter;
import cn.jsu.oj.judgment.net.starter.ServiceStarter;
import cn.jsu.oj.judgment.pojo.AbstractPack;
import cn.jsu.oj.judgment.satellite.util.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 判题机结果写回通道处理器
 */
@Slf4j
@Component("judgeWriteClientHandler")
@ChannelHandler.Sharable
public class JudgeWriteClientHandler extends ChannelInboundHandlerAdapter {

    public static Channel channel;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channel = ctx.channel();
        ServiceStarter.judgeWriteActiveSign = true;
        super.channelActive(ctx);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        AbstractPack abstractPack = (AbstractPack) msg;
        if (abstractPack.getTypeNo() != 92) {
            if (!ServiceStarter.judgeWriteVerifySign) {
                super.channelRead(ctx,msg);
            }
        }
        handle(msg);
        super.channelRead(ctx, msg);
    }

    private void handle(Object msg) throws InterruptedException {
        AbstractPack pack = (AbstractPack) msg;
        CommandPack<?> commandPack = new CommandPack<>(channel, pack);
        CmdHandleFactory.getHandle(pack.getTypeNo()).handle(commandPack);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channel.close();
        ServiceStarter.judgeWriteActiveSign = false;
        ServiceStarter.judgeWriteVerifySign = false;
        JudgeFactory judgeStarterFactory = (JudgeFactory) SpringUtil.getBean("judgeStarterFactory");
        ((JudgeStarter) Objects.requireNonNull(judgeStarterFactory).getProduct((short) 101)).start();
        ((JudgeStarter) Objects.requireNonNull(judgeStarterFactory).getProduct((short) 102)).start();
        super.channelInactive(ctx);

    }
}
